package com.example.demo02.utils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;


@Component
public class FileUtil {
    //文件上传
    public static String BASE_URL = "D:\\IDEA\\code\\MyFile";
    public static String uploadFile(MultipartFile file) throws IOException {
        String realfilename = file.getOriginalFilename();
        String newFilename = null;
        if (realfilename != null) {
            newFilename = getFileName(realfilename);
        }

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        String datePath = dateFormat.format(new Date());
        File targetPath = new File(BASE_URL , datePath);
        System.out.println(targetPath);
        if (!targetPath.exists()){
            targetPath.mkdirs();
        }

        File targetFilename = null;
        if (newFilename != null) {
        targetFilename = new File( targetPath , newFilename);
        }
        System.out.println(targetFilename);
        try {
            if (targetFilename != null) {
                file.transferTo(targetFilename);
            }
        return "MyFile/" + datePath + "/" + newFilename;
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    public static String getFileName(String filename) {
        String[] split = filename.split("\\.");
        String exten = split[split.length - 1];
        String name = UUID.randomUUID().toString().replace("-", "") + "." + exten;
        return name;
    }

    public static void deleteFile(String url) {
        File file = new File(BASE_URL + "\\" + url);
        file.delete();
    }

}
